package edu.ccut.saturn.basecomponent.xmloperationcomponent;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnComponentException;

public class GetRootByPathOrInputStream extends DefaultComponent {
	@Override
	public void execute(IParameterContext parameterContext) throws Exception {
		
		Document document = getDocument(parameterContext);
		
		if (document != null){
			Element root = document.getRootElement();
			
			parameterContext.setParameter(0, root);
		} else{
			parameterContext.setParameter(0, null);
		}
	}

	private Document getDocument(IParameterContext parameterContext)
			throws DocumentException, SaturnComponentException {
		
		Reader reader = (Reader)parameterContext.getParameterValue(3);
		
		InputStream is = null;
		
		String path = null;
		
		if (reader == null){
			
			is = (InputStream)parameterContext.getParameterValue(2);
			
			if (is == null){
				path = (String)parameterContext.getParameterValue(1);
			}
		}
		
		Document document = null;
		
		if (reader != null){
			try {
				document = new SAXReader().read(reader);
				
			} catch (Exception e) {
				e.printStackTrace();
				throw new SaturnComponentException("Don't get any XML file");
			} finally{
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		if (is != null){
			try {
				document = new SAXReader().read(is);	
				
			} catch (Exception e) {
				e.printStackTrace();
				throw new SaturnComponentException("Don't get any XML file");
			} finally{
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		if (path != null && "".equals(path.trim())){
			document = new SAXReader().read(path);
		}
		
		if (document == null){
			throw new SaturnComponentException("Don't get any XML file");
		}
		return document;
	}
}